<template>
  <div class="login">
    <div class="login-box">

      <el-form ref="ruleFormRef" style="max-width: 600px" :model="formData" status-icon :rules="rules" label-width="auto"
        class="rule-form">
        <div style="display: flex;">
          <el-image style="width: 50%; height: 50%; margin:20px auto;" src="https://webman.wyx2013.cn/logo.jpg"
            fit="fill" />
        </div>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
import { ElMessage } from "element-plus";
import http from "@/utils/axios.js";
import { checkToken,clearCache } from "@/utils/axios.js";
import UserStores from "@/stores/user.js";

const ruleFormRef = ref();
const formData = reactive({ username: undefined, password: undefined });
const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});
async function submitForm(formEl) {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      clearCache();
      http.post('app/pan/index/login', formData).then(res => {
        res.expires = (new Date()).getTime() + res.expires_in * 1000
        const obj = JSON.stringify(res)
        localStorage.setItem("webman_token", obj);
        checkToken(res)
        const { initUser } = UserStores()
        initUser(res)
        router.push({ path: '/' })
      }).catch(error => {
        ElMessage.error(error)
      })
    } else {
      ElMessage('请检查用户名和密码');
    }
  })
}
function resetForm(formEl) {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped>
.login {
  background: url(https://demo.buildadmin.com/assets/bg-95f82371.jpg) repeat;
  position: absolute;
  top: 0;
  display: flex;
  width: 100vw;
  height: 100vh;
  align-items: center;
  justify-content: center;
}

.login-box {
  background-color: rgb(119, 123, 143);
  max-width: 500px;
  max-height: 600px;
  width: 100%;
  height: 100%;

}

.rule-form {
  padding: 3rem;
}
</style>
